package com.dpf.api.utills;


import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class MyAESUtil {
    /**
     * AES 加密
     * @return 加密结果
     * @throws Exception 异常
     */
    public static void main(String[] args) throws Exception {
        String plainText = "admin123";

        System.out.println(AESEncrypt(plainText));
        System.out.println(AESDecrypt(AESEncrypt(plainText)));
    }


    /**
     * 获取AES编码规则
     * 定义密钥和向量
     *
     * @return
     */
    public static byte[] genEncodeRule() throws Exception {
        // 定义密钥和向量
        return "jsi43idkw6mqk12i".getBytes("utf-8");
    }

    /**
     * AES加密
     *
     * @param content 参数
     * @return
     */
    public static String AESEncrypt(String content) throws Exception {
        // 加密
        SecretKeySpec keySpec = new SecretKeySpec(genEncodeRule(), "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(genEncodeRule());
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
        byte[] encryptedBytes = cipher.doFinal(content.getBytes());
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    /**
     * AES解密
     *
     * @param content 加密后的值
     * @return
     */
    public static String AESDecrypt(String content) throws Exception {
        // 解密
        SecretKeySpec keySpec = new SecretKeySpec(genEncodeRule(), "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(genEncodeRule());
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
        byte[] decode = Base64.getDecoder().decode(content);
        byte[] decryptedBytes = cipher.doFinal(decode);
        return new String(decryptedBytes, "UTF-8");
    }


}
